<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2021/8/9
 * Time: 10:30
 */

namespace app\api\controller;


use think\Db;

class Assess extends Base
{
    private $user_id;
    private $create_time;
    private $page;
    
    /**
     * 异地登录验证
     * @return string
     */
    public function __construct()
    {
        $this->user_id = input('user_id');
        $this->page = input('page') ? input('page') : 1;
        $this->create_time = date('Y-m-d H:i:s');
    }
    
    /**
     * 分类
     * @return \think\response\Json
     */
    public function cateList(){
        $cate = Db::table('up_cate')
            ->where('cate_status', 1)
            ->field('cate_id, cate_name')
            ->select();
        if($cate){
            return json(['status' => 200, 'msg' => $cate]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 品牌列表
     * @return \think\response\Json
     * cate_id       分类ID
     */
    public function brandList(){
        $cate_id = input('cate_id');
        $brand = Db::table('up_brand')
            ->where('brand_cate_id', 'like', '%,' . $cate_id . ',%')
            ->field('brand_id, brand_name')
            ->order('brand_sort desc')
            ->select();
        if($brand){
            return json(['status' => 200, 'msg' => $brand]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 型号列表
     * @return \think\response\Json
     * brand_id       品牌ID
     */
    public function modelsList(){
        $brand_id = input('brand_id');
        $cate_id = input('cate_id');
        $models = Db::table('up_models')
            ->where('models_brand_id', $brand_id)
            ->where('models_cate_id', $cate_id)
            ->where('models_status', 1)
            ->field('models_id, models_name, models_image')
            ->order('models_sort desc')
            ->select();
        if($models){
            return json(['status' => 200, 'msg' => $models]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 搜索历史
     * @return \think\response\Json
     */
    public function searchHistory(){
        $history = Db::table('up_search_history')
            ->where('history_user_id', $this->user_id)
            ->limit(10)
            ->order('history_time desc')
            ->column('history_word');
        if($history){
            return json(['status' => 200, 'msg' => $history]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 清空搜索历史
     * @return \think\response\Json
     */
    public function clearHistory(){
        try{
            Db::table('up_search_history')->where('history_user_id', $this->user_id)->delete();
            return json(['status' => 200, 'msg' => '清空成功']);
        }catch(\Exception $e){
            return json(['status' => 0, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 搜索型号列表
     * @return \think\response\Json
     * keyword       关键字
     */
    public function searchModelsList(){
        $keyword = trim(input('keyword'));
        $models = Db::table('up_models')
            ->where('models_name', 'like', '%' . $keyword . '%')
            ->where('models_status', 1)
            ->field('models_id, models_name, models_image')
            ->order('models_sort desc')
            ->select();
//        // 插入搜索历史
//        $have = Db::table('up_search_history')
//            ->where('history_user_id', $this->user_id)
//            ->where('history_word', $keyword)
//            ->find();
//        if(!$have){
//            Db::table('up_search_history')->insert([
//                'history_user_id' => $this->user_id,
//                'history_word' => $keyword,
//                'history_time' => $this->create_time
//            ]);
//        }
        if($models){
            return json(['status' => 200, 'msg' => $models]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 回收故障列表
     * @return \think\response\Json
     * models_id        型号ID
     */
    public function recycleList(){
        $models_id = input('models_id');
        $models = Db::table('up_models')->where('models_id', $models_id)->field('models_name')->find();
        $recycle = Db::table('up_recycle')
            ->where('recycle_models_id', $models_id)
            ->where('recycle_status', 1)
            ->field('recycle_id, recycle_name, recycle_is_more')
            ->order('recycle_sort desc')
            ->select();
        // 插入搜索历史
        $keyword = trim(input('keyword'));
        if($keyword && $this->user_id > 0){
            $have = Db::table('up_search_history')
                ->where('history_user_id', $this->user_id)
                ->where('history_word', $keyword)
                ->find();
            if(!$have){
                Db::table('up_search_history')->insert([
                    'history_user_id' => $this->user_id,
                    'history_word' => $keyword,
                    'history_time' => $this->create_time
                ]);
            }
        }
        if($models && $recycle){
            return json(['status' => 200, 'msg' => $recycle, 'models_name' => $models['models_name']]);
        }else{
            return json(['status' => 200, 'msg' => [], 'models_name' => $models['models_name']]);
        }
    }
    
    /**
     * 回收故障小项
     * @return \think\response\Json
     * recycle_id      回收故障ID
     */
    public function recycleInfo(){
        $recycle_id = input('recycle_id');
        $info = Db::table('up_recycle_info')
            ->where('ri_recycle_id', $recycle_id)
            ->where('ri_status', 1)
            ->field('ri_id, ri_name')
            ->order('ri_time desc')
            ->select();
        if($info){
            return json(['status' => 200, 'msg' => $info]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 回收详情展示
     * @return \think\response\Json
     * models_id       型号ID
     * ri_ids          选择的回收故障小项ID，逗号隔开
     */
    public function recycleShow(){
        $models_id = input('models_id');
        $ri_ids = trim(input('ri_ids'),',');
    
        if(!$ri_ids) return json(['status' => 0, 'msg' => '请选择回收故障小项']);
        $models = Db::table('up_models')->where('models_id', $models_id)->field('models_name, models_max_recycle_price')->find();
        $info = Db::table('up_recycle_info')
            ->where('ri_id', 'IN', $ri_ids)
            ->field('ri_name, ri_price, ri_is_hb')
            ->select();
        $price = 0; // 总抵扣金额
        $tag = 2; // 1 环保回收    2 不是环保回收
        $info_arr = []; // 回收故障小项
        foreach($info as $k => $v){
            array_push($info_arr, $v['ri_name']);
            $price += $v['ri_price'];
            if($v['ri_is_hb'] == 1){
                $tag = 1;
            }
        }
        $data = [
            'models_name' => $models['models_name'],
            'info' => $info_arr,
            'recycle_price' => $models['models_max_recycle_price'] - $price,
            'tag' => $tag
        ];
        return json(['status' => 200, 'msg' => $data]);
    }
    
    /**
     * 店铺列表
     * @return \think\response\Json
     * shi_id        市ID
     * lon           经度
     * lat           纬度
     */
    public function shopList(){
        $shi_id = input('shi_id');
        $lon = input('lon');
        $lat = input('lat');
        $shop = Db::table('up_shop')
            ->join('up_area a1', 'a1.district_id = shop_sheng', 'LEFT')
            ->join('up_area a2', 'a2.district_id = shop_shi', 'LEFT')
            ->join('up_area a3', 'a3.district_id = shop_qu', 'LEFT')
            ->where('shop_shi', $shi_id)
            ->where('shop_status', 1)
            ->field("shop_id, shop_name, shop_addr, a1.district sheng, a2.district shi, a3.district qu, 
            ROUND(6378.138 * 2 * ASIN(SQRT(POW(SIN(($lat* PI() / 180 - shop_lat * PI() / 180) / 2),2) + COS($lat * PI() / 180) * COS(shop_lat * PI() / 180) * POW(SIN(($lon * PI() / 180 - shop_lon * PI() / 180) / 2),2))) * 1000) AS distance")
            ->order('distance asc')
            ->select();
        if($shop){
            foreach ($shop as $k => $v){
                if($v['distance'] < 1000){
                    $shop[$k]['distance'] = $v['distance'] . 'm';
                }else{
                    $shop[$k]['distance'] = round($v['distance'] / 1000,1) . ' km';
                }
            }
            return json(['status' => 200, 'msg' => $shop]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 默认地址
     * @return \think\response\Json
     */
    public function defaultAddr(){
        $addr = Db::table('up_user_address')
            ->join('up_area a1', 'a1.district_id = addr_sheng', 'LEFT')
            ->join('up_area a2', 'a2.district_id = addr_shi', 'LEFT')
            ->join('up_area a3', 'a3.district_id = addr_qu', 'LEFT')
            ->where('addr_user_id', $this->user_id)
            ->where('addr_status', 1)
            ->where('addr_is_default', 1)
            ->field('addr_id, addr_name, addr_phone, a1.district sheng, a2.district shi, a3.district qu, 
            addr_address')
            ->find();
        if($addr){
            return json(['status' => 200, 'msg' => $addr]);
        }else{
            return json(['status' => 200, 'msg' => []]);
        }
    }
    
    /**
     * 提交出售订单
     * @return \think\response\Json
     * order_price       出售金额
     * models_id         型号ID
     * ri_ids            回收故障小项ID，逗号隔开
     * shop_id           店铺ID
     * remark            备注
     */
    public function commitSaleOrder(){
        $order_tag = input('tag');
        $order_name = input('name');
        $order_phone = input('phone');
        $order_price = input('order_price');
        $order_models_id = input('models_id');
        $order_ri_ids = trim(input('ri_ids'),',');
        $order_shop_id = input('shop_id');
        $order_remark = input('remark');
        $models = Db::table('up_models')
            ->where('models_id', $order_models_id)
            ->field('models_brand_id, models_cate_id')
            ->find();
        $order_number = 'sale_' . date('YmdHis') . rand(1000, 9999);
        
        $insert = [
            'order_type' => 1,
            'order_tag' => $order_tag,
            'order_name' => $order_name,
            'order_phone' => $order_phone,
            'order_user_id' => $this->user_id,
            'order_number' => $order_number,
            'order_old_price' => $order_price,
            'order_time' => $this->create_time,
            'order_shop_id' => $order_shop_id,
            'order_cate_id' => $models['models_cate_id'],
            'order_brand_id' => $models['models_brand_id'],
            'order_models_id' => $order_models_id,
            'order_ri_ids' => $order_ri_ids,
            'order_remark' => $order_remark
        ];
        $order_id = Db::table('up_order')->insertGetId($insert);
        
        if($order_id){
            return json(['status' => 200, 'msg' => $order_id]);
        }else{
            return json(['status' => 0, 'msg' => '提交失败']);
        }
    }
    
    /**
     * 提交寄存订单
     * @return \think\response\Json
     * models_id         型号ID
     * ri_ids            回收故障小项ID，逗号隔开
     * shop_id           店铺ID
     * days              寄存天数
     * order_jc_price    寄存价格
     * serve_price       寄存保管费
     * remark            备注
     */
    public function commitJcOrder(){
        $order_tag = input('tag');
        $order_name = input('name');
        $order_phone = input('phone');
        $order_models_id = input('models_id');
        $order_ri_ids = trim(input('ri_ids'),',');
        $order_shop_id = input('shop_id');
        $order_days = (int)input('days');
        $order_jc_price = input('order_jc_price');
        $order_serve_price = input('serve_price');
        $order_remark = input('remark');
        if($order_days < 3 || $order_days > 30){
            return json(['status' => 0, 'msg' => '续存天数不能低于3天或大于30天']);
        }
        $models = Db::table('up_models')
            ->where('models_id', $order_models_id)
            ->field('models_brand_id, models_cate_id')
            ->find();
        $order_number = 'consign_' . date('YmdHis') . rand(1000, 9999);
        $oi_order_number = 'ci_' . date('YmdHis') . rand(1000, 9999);
        $dq_time = date('Y-m-d H:i:s', strtotime("+{$order_days}days"));
        $dq_date = date('Y-m-d', strtotime("+{$order_days}days"));
        
        Db::startTrans();
        try{
            // 插入订单表
            $insert = [
                'order_type' => 2,
                'order_tag' => $order_tag,
                'order_name' => $order_name,
                'order_phone' => $order_phone,
                'order_user_id' => $this->user_id,
                'order_number' => $order_number,
                'order_old_price' => $order_jc_price,
                'order_jc_now_price' => $order_jc_price,
                'order_jc_total_days' => $order_days,
                'order_jc_days' => $order_days,
                'order_jc_sy_days' => $order_days,
                'order_jc_price' => $order_serve_price,
                'order_jc_datetime' => $dq_time,
                'order_time' => $this->create_time,
                'order_shop_id' => $order_shop_id,
                'order_cate_id' => $models['models_cate_id'],
                'order_brand_id' => $models['models_brand_id'],
                'order_models_id' => $order_models_id,
                'order_ri_ids' => $order_ri_ids,
                'order_remark' => $order_remark,
                'order_jc_date' => $dq_date
            ];
            $order_id = Db::table('up_order')->insertGetId($insert);
            
            // 插入订单续存表
            $insert_info = [
                'oi_order_id' => $order_id,
                'oi_days' => $order_days,
                'oi_price' => $order_serve_price,
                'oi_date' => $dq_date,
                'oi_datetime' => $dq_time,
                'oi_time' => $this->create_time,
                'oi_order_number' => $oi_order_number
            ];
            Db::table('up_order_info')->insert($insert_info);
            
            Db::commit();
            return json(['status' => 200, 'msg' => $order_id]);
        }catch(\Exception $e){
            Db::rollback();
            return json(['status' => 200, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 根据天数获取保管费
     * @return \think\response\Json
     * days      天数
     */
    public function getServePrice(){
        $days = input('days');
        $serve_price = Db::table('up_serve_price')
            ->where('sp_days', $days)
            ->value('sp_price');
        if($serve_price){
            return json(['status' => 200, 'msg' => $serve_price]);
        }else{
            return json(['status' => 200, 'msg' => '']);
        }

    }
}